package service;

import JDBC.DBUtils;
import method.Encryption;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * people can get their own account in here
 */
@WebServlet(name = "Register")
public class Register extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        String PhoneNumber=req.getParameter("PhoneNumber");
        String passwordStr=req.getParameter("Password");
        String password  = "";
        String answer="false";

        try {
            password = Encryption.aesDecodeStr(passwordStr,"wwwwwwwwwwwwwww1wwwwwwwwwwwwwww1");
        } catch (Exception e) {
            e.printStackTrace();
            PrintWriter out = resp.getWriter();
            String str ="{\"answer\":\""+answer+"\"}";
            out.println(str);
            out.flush();
            out.close();
        }

        String name=req.getParameter("Name");
        String AccountName=req.getParameter("AccountName");
        String Deposit=req.getParameter("Deposit");
        if(Deposit==null) {
            System.out.println("no deposit");
            answer = DBUtils.register(PhoneNumber, password, AccountName, name);
        }
        else{
            double deposit=Double.parseDouble(Deposit);
            answer=DBUtils.register(PhoneNumber, password, AccountName, name, (int) deposit);
        }
        PrintWriter out = resp.getWriter();
        String str ="{\"answer\":\""+answer+"\"}";
        out.println(str);
        out.flush();
        out.close();

    }
}
